//
//  AppDelegate.m
//  EditMarkDown
//
//  Created by 丁玉松 on 2018/9/24.
//  Copyright © 2018年 丁玉松. All rights reserved.
//

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    
    [[NSAppleEventManager sharedAppleEventManager] setEventHandler:self andSelector:@selector(handleURLEvent:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];
}

- (void)handleURLEvent:(NSAppleEventDescriptor*)theEvent withReplyEvent:(NSAppleEventDescriptor*)replyEvent {
    
    NSString* path = [[theEvent paramDescriptorForKeyword:keyDirectObject] stringValue];
    
    NSURL *url = [NSURL URLWithString:path];

    NSString *rpath = [url.absoluteString substringFromIndex:9];
    NSString *transString = [rpath stringByRemovingPercentEncoding];
    NSString *fullFilePath = [NSString stringWithFormat:@"%@/mine/survival/%@",NSHomeDirectory(),transString];
    [self cmd:fullFilePath];
}

- (NSString *)cmd:(NSString *)cmd
{
    NSTask *task = [[NSTask alloc] init];

    [task setLaunchPath: @"/usr/bin/open"];
    NSArray *arguments = [NSArray arrayWithObjects: @"-aTypora", cmd, nil];
    [task setArguments: arguments];
    // -c 用来执行string-commands（命令字符串），也就说不管后面的字符串里是什么都会被当做shellcode来执行
//    NSArray *arguments = [NSArray arrayWithObjects: @"-c", cmd, nil];
//    [task setArguments: arguments];
    
    // 新建输出管道作为Task的输出
    NSPipe *pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];
    
    // 开始task
    NSFileHandle *file = [pipe fileHandleForReading];
    [task launch];
    
    // 获取运行结果
    NSData *data = [file readDataToEndOfFile];
    return [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
}

@end
